#include <vector>
#include <climits>
#include <algorithm>
#include <numeric>
#include <iostream>

class Solution
{
public:
	int candy(std::vector<int>& ratings)
	{
		int length = ratings.size();
		if (length == 0) return 0;
		else if (length == 1) return 1;

		auto IntMax = std::numeric_limits<int>::max();

		std::vector<int> nums(length, 1);
		for (int i = 0; i < length; i++) {
			auto _last = (0 <= i - 1) ? ratings[i - 1] : IntMax;
			auto _this = ratings[i];
			auto _next = (i + 1 < length) ? ratings[i + 1] : IntMax;
			if (_last == IntMax) {
				for (int j = i + 1; j<length; j++)
					if (ratings[j] > ratings[j - 1])
						nums[j] = std::max(nums[j], nums[j - 1] + 1);
					else break;
			} else if (_next == IntMax) {
				for (int j = i - 1; j >= 0; j--)
					if (ratings[j] > ratings[j + 1])
						nums[j] = std::max(nums[j], nums[j + 1] + 1);
					else break;
			} else if (_last >= _this && _next >= _this && _last + _next > 2 * _this) {
					for (int j = i + 1; j<length; j++)
						if (ratings[j]>ratings[j - 1])
							nums[j] = std::max(nums[j], nums[j - 1] + 1);
						else break;
					for (int j = i - 1; j >= 0; j--)
						if (ratings[j] > ratings[j + 1])
							nums[j] = std::max(nums[j], nums[j + 1] + 1);
						else break;
			}
		}
		return std::accumulate(nums.cbegin(), nums.cend(), 0);
	}
};